import React, { useState, useEffect } from 'react';
import CurrencyInput from './CurrencyInput';
import './currency.css';

interface ExchangeRateData {
    [currency: string]: {
        [targetCurrency: string]: number;
    };
}

// 货币选项类型
type CurrencyCode = 'USD' | 'CNY' | 'EUR' | 'GBP' | 'JPY';

const CurrencyConverter: React.FC = () => {
    const [currencies, setCurrencies] = useState<CurrencyCode[]>([]);
    const [amount, setAmount] = useState<number>(1);
    const [fromCurrency, setFromCurrency] = useState<CurrencyCode>('USD');
    const [toCurrency] = useState<CurrencyCode>('CNY');
    const [exchangeRate, setExchangeRate] = useState<number>(0);
    const [convertedAmount, setConvertedAmount] = useState<number>(0);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);

    // 模拟API获取汇率数据
    useEffect(() => {
        const fetchExchangeRate = async () => {
            try {
                // 实际项目中应使用真实API，如Open Exchange Rates或Fixer
                const mockRates: ExchangeRateData = {
                    USD: { CNY: 7.2, EUR: 0.92, GBP: 0.79, JPY: 145.8 ,USD:1},
                    CNY: { USD: 0.14, EUR: 0.13, GBP: 0.11, JPY: 20.25 ,CNY:1},
                    EUR: { USD: 1.09, CNY: 7.83, GBP: 0.86, JPY: 158.5,EUR:1 },
                    GBP: { USD: 1.27, CNY: 9.1, EUR: 1.16, JPY: 184.6 ,GBP:1},
                    JPY: { USD: 0.0069, CNY: 0.049, EUR: 0.0063, GBP: 0.0054 ,JPY:1}
                };

                // 模拟网络延迟
                await new Promise(resolve => setTimeout(resolve, 500));

                if (!mockRates[fromCurrency] || !mockRates[fromCurrency][toCurrency]) {
                    console.info('mockRates[fromCurrency',mockRates[fromCurrency]);
                    console.info('mockRates[fromCurrency][toCurrency]',mockRates[fromCurrency][toCurrency]);
                    throw new Error('汇率数据不可用');
                }

                const rate = mockRates[fromCurrency][toCurrency];
                setExchangeRate(rate);
                setConvertedAmount(amount * rate);
                setCurrencies(Object.keys(mockRates) as CurrencyCode[]);
                setLoading(false);
            } catch (err) {
                if (err instanceof Error) {
                    setError(err.message);
                } else {
                    setError('获取汇率时发生未知错误');
                }
                setLoading(false);
            }
        };

        fetchExchangeRate();
    }, [fromCurrency, toCurrency, amount]);

    // 处理金额变化
    const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = parseFloat(e.target.value);
        if (!isNaN(value)) {
            setAmount(value);
        }
    };

    // 处理货币选择变化
    const handleFromCurrencyChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        setFromCurrency(e.target.value as CurrencyCode);
    };

    return (
        <div className="currency-converter">
            <h2>实时汇率转换</h2>

            {loading && <p>加载汇率数据中...</p>}
            {error && <p className="error">{error}</p>}

            {!loading && !error && (
                <>
                    <CurrencyInput
                        amount={amount}
                        currency={fromCurrency}
                        currencies={currencies}
                        onAmountChange={handleAmountChange}
                        onCurrencyChange={handleFromCurrencyChange}
                    />

                    <div className="conversion-info">
                        <p>1 {fromCurrency} = {exchangeRate.toFixed(4)} {toCurrency}</p>
                        <i className="fa fa-exchange" aria-hidden="true"></i>
                    </div>

                    <CurrencyInput
                        amount={convertedAmount}
                        currency={toCurrency}
                        currencies={currencies}
                        readOnly
                    />

                    <div className="last-update">
                        <p>汇率更新时间: {new Date().toLocaleString()}</p>
                    </div>
                </>
            )}
        </div>
    );
};

export default CurrencyConverter;